package aar.test.tessocr.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.CustomFooterViewCallBack;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import aar.test.tessocr.EventMessage.EventMessage;
import aar.test.tessocr.EventMessage.MessageEvent;
import aar.test.tessocr.OpenCabActivity;
import aar.test.tessocr.adapter.LanListAdapter;
import aar.test.tessocr.adapter.OrderListAdapter;
import aar.test.tessocr.baseApplication.BaseApplication;
import aar.test.tessocr.model.DialogCallback;
import aar.test.tessocr.model.LanListModel;
import aar.test.tessocr.model.LzyResponse;
import aar.test.tessocr.model.LanListModel;
import aar.test.tessocr.utils.ConstantPara;
import aar.test.tessocr.utils.PrefUtils;
import aar.test.tessocr.utils.ScreenUtil;
import aar.test.tessocr.utils.Urls;
import aar.test.tessocr.utils.Utils;
import aar.test.tessocr.view.CustomDialog;
import aar.test.tessocr.view.CustomLoadingMoreFooter;
import butterknife.BindView;
import clx.tessocr.ocreng.R;
import okgo.OkGo;
import okgo.callback.StringCallback;
import okgo.model.Response;
import okhttp3.RequestBody;

import static aar.test.tessocr.Login1Activity.JSON;

/**
 * 已揽件（未支付）
 * Created by sunshine on 2020/10/20
 */
public class OrderTakenNoPayedFragment extends BaseFragment implements XRecyclerView.LoadingListener{
    @BindView(R.id.rvData)
    XRecyclerView rvData;
    @BindView(R.id.ll_empty)
    LinearLayout imgEmpty;

    private List<LanListModel> mList = new ArrayList<>();
    private LanListAdapter mAdapter;
    private boolean isFirst = true;
    private int pageNum = 1;
    private String search = "";
    private CustomDialog commitDialog;
    EditText editText;
    EditText edit_ydh;
    ImageView btn_confirm;
    boolean isPayed;
    private String cabinetId = "";

    public static OrderTakenNoPayedFragment newInstance(String orderType, String search, String cabinetId) {
        OrderTakenNoPayedFragment fragment = new OrderTakenNoPayedFragment();
        Bundle bundle = new Bundle();
        bundle.putString("orderType", orderType);
        bundle.putString("search", search);
        //bundle.putBoolean("isPayed", isPayed);
        bundle.putString("cabinetId", cabinetId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void setUpContentView() {
        setContentView(R.layout.fragment_order_delivered);
    }

    @Override
    protected void setUpView(View view) {

    }

    @Override
    protected void setUpComponent() {
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        rvData.setLayoutManager(manager);
        mAdapter = new LanListAdapter(getActivity(), mList, false, false);
        rvData.setAdapter(mAdapter);
        final CustomLoadingMoreFooter footer = new CustomLoadingMoreFooter(getActivity());
        rvData.setFootView(footer, new CustomFooterViewCallBack() {
            @Override
            public void onLoadingMore(View yourFooterView) {
                footer.onLoadingMore();
            }

            @Override
            public void onLoadMoreComplete(View yourFooterView) {
                footer.onLoadMoreComplete();
            }

            @Override
            public void onSetNoMore(View yourFooterView, boolean noMore) {
                footer.onSetNoMore();
            }
        });
        rvData.setPullRefreshEnabled(true);
        rvData.setLoadingMoreEnabled(true);
        rvData.setLoadingListener(this);
    }

    @Override
    protected void setUpData() {

    }

    @Override
    public void onRefresh() {
        pageNum = 1;
        getData();
    }

    @Override
    public void onLoadMore() {
        getData();
    }

    @Override
    public void onResume() {
        super.onResume();
        //recruitType = getArguments().getInt(Constants.RECRUIT_TYPE);
        search = getArguments().getString("search");
        //isPayed = getArguments().getBoolean("isPayed");
        cabinetId = getArguments().getString("cabinetId");

        if (isFirst) {
            isFirst = false;
            refreshData();
        }
    }

    private void refreshData() {
        pageNum = 1;
        getData();
    }

    private void getData() {
        if (TextUtils.isEmpty(PrefUtils.getString(getActivity(), "userId", ""))) {
            Toast.makeText(getActivity(), "登录信息为空", Toast.LENGTH_SHORT).show();
            return;

        }

        final Map<String, Object> map = new HashMap<>();
        map.put("adminid", PrefUtils.getString(getActivity(), "userId", ""));
        map.put("keyword", search);
        map.put("payStatus", "2");
        map.put("page", pageNum);
        map.put("size", ConstantPara.PAGESIZE);
        map.put("cabinetId", cabinetId);

        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<LzyResponse<List<LanListModel>>>post(Urls.URL_HAS_RECEIVED)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse<List<LanListModel>>>(getActivity()) {
                    @Override
                    public void onSuccess(Response<LzyResponse<List<LanListModel>>> response) {
                        Log.e("OrderListActivity","UnDeliveredonSuccess--------------------"+response.body().data.toString());
                        if (pageNum == 1) {
                            mList.clear();
                        }

                        mList.addAll(response.body().data);
                        if (null == mList || mList.size() == 0) {
                            imgEmpty.setVisibility(View.VISIBLE);
                        } else {
                            imgEmpty.setVisibility(View.GONE);
                        }

                        if (null == response.body().data || response.body().data.size() == 0) {
                            rvData.refreshComplete();
                            rvData.loadMoreComplete();
                            rvData.setNoMore(true);

                            return;
                        } else {
                            if (null != response.body().data && response.body().data.size() > 0) {
                                rvData.refreshComplete();
                                pageNum++;

                                mAdapter.notifyDataSetChanged();

                                mAdapter.setViewClickListener(new LanListAdapter.ViewClickListener() {
                                    @Override
                                    public void post_again(int pos) {
                                        courierHasPaidByCash(pos);
                                    }

                                    @Override
                                    public void gridTackBack(int pos) {
                                        noticeUserPayFreight(pos);
                                    }

                                    @Override
                                    public void returnId(int pos) {
                                        returnOrderId(pos);
                                    }
                                });
                            }
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<List<LanListModel>>> response) {
                        if (pageNum == 1) {
                            imgEmpty.setVisibility(View.VISIBLE);
                            mList.clear();
                            mAdapter.notifyDataSetChanged();
                        }
                        rvData.refreshComplete();
                        rvData.loadMoreComplete();
                        rvData.setNoMore(true);

                    }
                });
    }

    private void returnOrderId(int pos) {
        showReturnOrderIdDialog(pos);
    }

    private void showReturnOrderIdDialog(int pos) {
        View view = View.inflate(getActivity(), R.layout.dialog_return_orderid, null);
        initregisterDialogView(view, pos);
        commitDialog = new CustomDialog(getActivity(), ScreenUtil.dp2px(getActivity(), 270), ScreenUtil.dp2px(getActivity(), 300),
                view, R.style.CustomDialog);
        commitDialog.show();
    }

    private void initregisterDialogView(View view, final int pos) {
        //ImageView imgClose = view.findViewById(R.id.img_dialog_register_activity_close);
        Button btnConfirmDelete = view.findViewById(R.id.btn_dialog_register_activity_submit);
        Button btnScan = view.findViewById(R.id.scan);
        editText = view.findViewById(R.id.et_fei);
        edit_ydh = view.findViewById(R.id.et_order_id);
        btn_confirm = view.findViewById(R.id.img_cancel);

        btnScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), OpenCabActivity.class);
                intent.putExtra("isFromReturnOrderId", true);
                startActivity(intent);
            }
        });

        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeDialog();
            }
        });

        btnConfirmDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (edit_ydh.getText().toString().trim().equals("")) {
                    Toast.makeText(getActivity(), "请回填运单号", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (editText.getText().toString().trim().equals("")) {
                    Toast.makeText(getActivity(), "请输入运费金额", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (editText.getText().toString().trim().equals("0")) {
                    Toast.makeText(getActivity(), "运费金额为大于0的整数", Toast.LENGTH_SHORT).show();
                    return;
                }

                Map<String, Object> map = new HashMap<>();
                map.put("id", mList.get(pos).getId());
                map.put("express_order",edit_ydh.getText().toString().trim());
                map.put("freight",editText.getText().toString().trim());

                Gson gg = new Gson();
                String json = gg.toJson(map);

                RequestBody body = RequestBody.create(JSON, json);
                OkGo.<String>post(Urls.URL_UPDATE_EXPORDER)//
                        .tag(this)//
                        .upRequestBody(body)
                        .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {

                                Log.e("SiteDispatchActivity", "onSuccess-----logout---------------" + response.body());
                                try {
                                    JSONObject jsonObject = new JSONObject(response.body());
                                    if (jsonObject.has("code")) {
                                        String code = jsonObject.getString("code");
                                        if (TextUtils.equals(code, "200")) {
                                            String msg = jsonObject.getString("msg");
                                            Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                                        } else if (TextUtils.equals(code, "100")) {
                                            String msg = jsonObject.getString("msg");
                                            Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                                            mList.get(pos).setExpress_order(edit_ydh.getText().toString().trim());
                                            mList.get(pos).setFreight(editText.getText().toString().trim());
                                            mAdapter.notifyDataSetChanged();
                                            closeDialog();
                                        }
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }
                        });
            }
        });
    }

    private void closeDialog() {
        if (commitDialog != null && commitDialog.isShowing()) {
            commitDialog.dismiss();
        }
    }

    private void courierHasPaidByCash(final int pos) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", mList.get(pos).getId());


        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<String>post(Urls.URL_PAY_BY_CASH)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        Log.e("SiteDispatchActivity", "onSuccess-----logout---------------" + response.body());
                        try {
                            JSONObject jsonObject = new JSONObject(response.body());
                            if (jsonObject.has("code")) {
                                String code = jsonObject.getString("code");
                                if (TextUtils.equals(code, "200")) {
                                    String msg = jsonObject.getString("msg");
                                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                                } else if (TextUtils.equals(code, "100")) {
                                    String msg = jsonObject.getString("msg");
                                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                                    mList.remove(pos);
                                    mAdapter.notifyDataSetChanged();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    private void noticeUserPayFreight(int pos) {


        Map<String, Object> map = new HashMap<>();
        map.put("id", mList.get(pos).getId());


        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<String>post(Urls.URL_NOTICE_FREIGHT)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        Log.e("SiteDispatchActivity", "onSuccess-----logout---------------" + response.body());
                        try {
                            JSONObject jsonObject = new JSONObject(response.body());
                            if (jsonObject.has("code")) {
                                String code = jsonObject.getString("code");
                                if (TextUtils.equals(code, "200")) {
                                    String msg = jsonObject.getString("msg");
                                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                                } else if (TextUtils.equals(code, "100")) {
                                    String msg = jsonObject.getString("msg");
                                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onShutDown(MessageEvent eventMsg) {
        String msg = eventMsg.getMessage();
        if (eventMsg.getType() == 2) {
            edit_ydh.setText(eventMsg.getMessage());
        }
    }
}
